import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { NavBar, Icon, Drawer, List, Button, Modal, Picker, Popover } from 'antd-mobile';
import { routerRedux } from 'dva/router';
import { connect } from "dva"
import styles from './Header.less';
let ListItem = List.Item;
import { goToPage, isNull } from "../utils/helper"
import { setLogout } from "../utils/request"
import MDrawer from "../components/MDrawer/MDrawer"
import MAction from "../components/MAction/MAction"
import MToast from '../components/Util/MToast';
import MIcon from '../components/MIcon';
import md5 from 'md5';
let config = {};
let allHomePath = [];
try {
	config = JSON.parse(JSON.parse(localStorage[MI_APP_CODE + "config"]))
}
catch (e) {

}
try {
	allHomePath = all_home_path
}
catch (e) {

}
console.log(config)
@connect(({ global, form }, props) => {
	let { location } = props;
	let { pathname, search } = location;
	let formDataKey = md5(pathname + search)
	return ({
		global: global,
		form: form[formDataKey]
	})
})
export default class Header extends PureComponent {
	constructor(props) {
		super(props);
		this.path = "";
		this.state = {
			titleArr: {
				"/create": "",
				"/edit": "",
				"/view": "",
				"/": "",
				"/page": "",
				"/map": "",
				"/changePassword": ""
			},
			showHeaderArr: ["/", "/create", "/edit", "/view", "/page", "/map", "/changePassword","/newLogin", "/goodsDetail", "/goodcart","/ungoodcart","/way","/addAddress","/addressList","/modifyAddress","/placeOrder","/my","/myOrder","/orderDetail","/searchPage","/chat", "/register","/category_page","/category_page1","/category_page2",,"/category_page3","/cash","/pay_success","/feedback"],
			open: false,
			selectKeys: {}
		}
	}
	componentWillReceiveProps(nextProps) {

	}
	onOpenChange = () => {
		this.setState({ open: !this.state.open });
	};
	registerRightNavigate = () => {
		let { location, global } = this.props;
		let { pathname, search } = location;
		let path = pathname + search
		if (path == "/" || path == "/login") {
			return;
		}
		if (isNull(global)) {
			return;
		}
		if (this.path == path) {
			return;
		}
		let { navigate } = global;
		if (!isNull(navigate)) {
			let rightNavigate = navigate[pathname + search];
			if (!isNull(rightNavigate) && !isNull(rightNavigate.navigate) && rightNavigate.navigate.length > 0) {
				this.path = path;
				let { navigate: currentNavigate, config } = rightNavigate;
				let rightNavigateClick = (obj) => {
					obj = JSON.parse(obj.data);
					let { type, event_key, key } = obj;
					if (type == "select" || type == "popover") {
						let { selectKeys } = this.state;
						let obj = {};
						for (let i in selectKeys) {
							obj[i + "_visible"] = false
						}
						obj[key + "_visible"] = true
						this.setState({
							...obj,
							selectKeys: {
								...selectKeys,
								[key]: 1
							}
						})
					}
					else {
						MAction({ ...this.props, config, formData: { ...this.props.form.formData } }, event_key)
					}
				}
				Func.registerHanderBridge("rightNavigateClick", rightNavigateClick);
				Func.callHander(bridge, "renderRightNavigate", { arr: currentNavigate, title: "右上角" });//arr为数组[{img:"",app_img:"",event_key:""}]
			}
			else {
				Func.callHander(bridge, "renderRightNavigate", { arr: [], title: "右上角" });//arr为数组[{img:"",app_img:"",event_key:""}]
				this.path = "";
			}
		}
		else {
			this.path = "";
		}
	}
	componentDidMount() {

	}
	componentDidMount() {
		let { location: { pathname, search } } = this.props;
		let formDataKey = md5(pathname + search);
		console.log("header-did", formDataKey);
	}
	render() {
		let { location, dispatch, global, isModal, form } = this.props;
		if (isNull(form)) {
			form = {}
		}
		let { headerTitle, navigate } = global;
		let { pathname, state, search } = location;
		let formDataKey = md5(pathname + search);
		let { titleArr, showHeaderArr, open } = this.state;
		if (showHeaderArr.indexOf(pathname) == -1) {
			return null
		}
		let title = state && state.title;
		if (isNull(title)) {
			title = headerTitle[pathname + search]
		}
		title = title || titleArr[pathname];
		let { default_page, default_page_title, globalMenu, globalLeftMenu: leftMenu } = global;
		title = default_page_title || title;
		document.title = localStorage[MI_APP_CODE + "website"] + " - " + title;
		if (browser.isInApp) {// 设置title
			Func.callHander(bridge, "setTitle", { "title": title });
		}

		if (globalMenu.length == 0 && pathname.indexOf("/register") == -1) {
			return null
		}
		let homePath = "";
		let isTabbar = false;
		console.log(globalMenu)
		globalMenu.map(item => {
			if (item.code == default_page) {
				homePath = item.path;
			}
			if (item.path == pathname + search) {
				isTabbar = true;
			}
			else if (allHomePath && allHomePath.length > 0) {
				if (allHomePath.includes(item.path)) {
					let to_path = localStorage[MI_APP_CODE + "to_path"];
					if (to_path == (pathname + search)) {
						localStorage.removeItem(MI_APP_CODE + "to_path");
					}
					if ((pathname + search).indexOf(item.path) != -1) {
						let right = (pathname + search).replace(item.path, '');
						if (right.length == 0 || right.substring(0, 1) == "&") {
							isTabbar = true;
						}
					}
				}
			}
		});
		let rightContent = [];
		let appRightContent = [];//保存 弹出窗
		if (!isNull(navigate)) {
			let rightNavigate = navigate[pathname + search];
			if (!isNull(rightNavigate) && !isNull(rightNavigate.navigate) && rightNavigate.navigate.length > 0) {
				rightNavigate.navigate.map((item) => {
					let { img, event_key, type, dataset_key, field, key } = item || {};
					if (type == "select" || type == "popover") {
						let headerList = form[dataset_key];
						if (isNull(headerList)) {
							headerList = []
						}
						let val;
						try {
							val = form.formData[field];
						}
						catch (e) {

						}
						let com;
						if (type == "popover") {
							com = <Popover
								key={-1}
								mask
								overlayClassName="mi-popover"
								overlayStyle={{ color: 'currentColor' }}
								visible={this.state[key + "_visible"]}
								placement="bottomRight"
								overlay={
									headerList.map((item, key) => {
										return <Popover.Item style={{ padding: "5px 20px" }} key={key} value={item.code} data={{ ...item }}>{item.name}</Popover.Item>
									})
								}
								align={{
									overflow: { adjustY: 0, adjustX: 0 },
									offset: [0, 0],
								}}
								onVisibleChange={this.handleVisibleChange}
								onSelect={(opt) => {
									let data = opt.props.data;//当前选中的数据
									let { event_key } = data;
									if (!isNull(event_key)) {//执行event_key,跳转页面
										console.log("1111", this.props)
										MAction({ ...this.props, config: rightNavigate.config, data: opt.props.data, formData: { ...opt.props.data, ...this.props.form.formData } }, event_key)
									}
									else {	// 改变当前from的formData
										dispatch({
											type: "form/setFormData",
											payload: {
												key: formDataKey,
												value: {
													[field]: opt.props.value
												}
											}
										})
									}
									this.setState({
										[key + "_visible"]: false,
									});
								}}
							>
								<img key={key} type="plus" style={{ width: "25px", height: "25px", marginLeft: "5px" }} src={img} onClick={() => this.setState({ [key + "_visible"]: true })} />
							</Popover>

						}
						else {
							com = <Picker
								key={key}
								visible={this.state[key + "_visible"]}
								data={
									headerList.map(i => {
										return { label: i.name, value: i.code }
									})
								}
								cols={1}
								value={[val]}
								onOk={(opt) => {
									// 改变当前from的formData
									dispatch({
										type: "form/setFormData",
										payload: {
											key: formDataKey,
											value: {
												[field]: opt[0]
											}
										}
									})
									this.setState({
										[key + "_visible"]: false,
									});
								}}
								onDismiss={() => this.setState({ [key + "_visible"]: false })}
							>
								<img key={key} type="plus" style={{ width: "25px", height: "25px", marginLeft: "5px" }} src={img} onClick={() => this.setState({ [key + "_visible"]: true })} />
							</Picker>

						}
						rightContent.push(com);
						if (browser.isInApp) {
							appRightContent.push(com);
						}
					}
					else {
						rightContent.push(<img key={key} type="plus" style={{ width: "25px", height: "25px", marginLeft: "5px" }} src={img} onClick={() => {
							MAction({ ...this.props, config: rightNavigate.config, formData: { ...this.props.form.formData } }, event_key)
						}
						} />)
					}
				})
			}
		}
		if (browser.isInApp) {//是否是嵌套在App里
			this.registerRightNavigate();
			return (
				<div style={{ width: "100%", height: 0, overflow: "hidden", position: "fixed", top: "-20px", right: "20px" }} data-flex="dir:right">
					{appRightContent}
				</div>
			);
		}
		let leftMenus = [];
		leftMenu.map((item, key) => {
			let { label, icon, path } = item;
			leftMenus.push(
				<ListItem key={key} arrow="horizontal" onClick={() => {
					goToPage({
						dispatch,
						config: { url: path }
					});
					this.setState({ open: false })
				}}>
					<div data-flex="dir:left cross:center">
						<img style={{ marginRight: "5px" }} src={icon} alt="" />
						<span>{label}</span>
					</div>
				</ListItem>
			)
		});
		// pathname+search===homePath时 是首页
		if (isTabbar) {
			console.log("是首页");
			localStorage[MI_APP_CODE + "isHome"] = "true";
			let drawerClass = "my-drawer";
			let wrapClass = "my-wrap";
			if (!open) {
				drawerClass += " my-drawer-close";
				wrapClass += " my-wrap-close";
				document.getElementById("root").style.overflow = ""
			}
			else {
				document.getElementById("root").style.overflow = "hidden"
			}
			let _icon = {
				icon: <img onClick={() => {
					this.onOpenChange()
				}} style={{ width: "30px", height: "30px" }} src="./image/menu.png" alt="" />
			};
			if (config.hide_left_menu == 1) {
				_icon = {}
			}
			return (<div className={styles.header} id="header">
				<NavBar
					{
					..._icon
					}
					rightContent={rightContent}
				>
					{default_page_title || title}
				</NavBar>
				<MDrawer open={open} onOpenChange={this.onOpenChange} className="header-drawer">
					<div className="header" data-flex="dir:left cross:center">
						<img src="./image/user.png" alt="" />
						{localStorage[MI_APP_CODE + "username"]}
					</div>
					<div className="list" style={{ overflow: "auto" }}>
						{
							leftMenu.length > 0 && <div style={{ marginTop: "20px" }}>
								{leftMenus}
							</div>
						}
						{
							config.hide_left_change_password != 1 && <div style={{ paddingLeft: "15px", height: "40px", lineHeight: "40px" }}>
								系统
						</div>
						}
						{/* <ListItem arrow="horizontal" onClick={() => {
							goToPage({
								dispatch,
								config: { url: "/page" }
							});
							this.setState({ open: false })
						}}>清除缓存</ListItem> */}
						{
							config.hide_left_change_password != 1 && <ListItem arrow="horizontal" onClick={() => {
								goToPage({
									dispatch,
									config: { url: "/changePassword?" }
								});
								this.setState({ open: false })
							}}>修改密码</ListItem>
						}

						{/* <ListItem arrow="horizontal" onClick={() => {
							goToPage({
								dispatch,
								config: { url: "/page" }
							});
							this.setState({ open: false });
						}}>系统</ListItem> */}
					</div>
					<div className="footer">
						<a href={localStorage[MI_APP_CODE + "copyright_url"]} style={{ color: "inherit" }}>{localStorage[MI_APP_CODE + "copyright"]} v{mi_version}</a>
						<Button style={{ background: "#ed4747", color: "#fff", borderRadius: "15px" }} size="default" onClick={() => {
							Modal.alert('温馨提示', '确定退出登录?', [{ text: '取消' },
							{
								text: '确定',
								onPress: () => {
									this.onOpenChange();
									setLogout();
								}
							}])
						}}>退出登录</Button>
					</div>
				</MDrawer>
			</div>);
		}
		else {
			console.log("不是首页");
			localStorage[MI_APP_CODE + "isHome"] = "false";
			return (
				<div className={styles.header} id="header">
					<NavBar
						mode="dark"
						icon={<img onClick={() => {
							try {
								let config = this.props.form.config;
								if (!isNull(config)) {
									let left_back_to_path = config.left_back_to_path;
									if (!isNull(left_back_to_path)) {
										if (left_back_to_path == -1) {
											window.location.go(-1)
										}
										else if (left_back_to_path.indexOf("http") == 0 || left_back_to_path.indexOf("https") == 0) {
											window.open(left_back_to_path)
										}
										else {
											dispatch(routerRedux.replace(left_back_to_path));
											if (left_back_to_path == "/") {
												setTimeout(() => {
													window.location.reload();
												}, 10);
											}
										}

										return;
									}
								}
							}
							catch (e) {

							}

							if (isModal) {
								this.props.closeModal()
							}
							else {
								dispatch(routerRedux.go(-1));
							}
						}} src="image/arrow_left.png" style={{ width: "25px", height: "25px" }} />}
						rightContent={rightContent}

					>{title}</NavBar>
				</div>
			)
		}
	}
}
Header.propTypes = {
	location: PropTypes.object.isRequired
};
